<?php
namespace app\sisome\controller;
use think\Request;
use think\Db;
class E extends Common{	//E计划后台
    public function index(){
    	// die('234');
        //return $this->fetch('hello',['name'=>'thinkphp']);
        //return view('hello',['name'=>'thinkphp']);
        // 方法    说明
        // fetch   渲染模板输出
        // display 渲染内容输出
        // assign  模板变量赋值
        // engine  初始化模板引擎
        return view();
    }
    public function user(){    //参与用户
        $lists=db('e_user')->where([])->order('uid desc')->paginate(10);
        $this->assign('lists', $lists);
        return view();
    }
    public function lun(){    //（重启）E计划列表
        $lists=db('e_lun')->where([])->order('lun desc')->paginate(10);
        $this->assign('lists', $lists);
        return view();
    }
    public function paidan(){    //排单池
        $lists=db('e_list')->where('lun','=','0')->order('jiasu desc,time_true asc')->paginate(10);
        $this->assign('lists', $lists);
        return view();
    }
    public function zijin(){    //资金池
        $num_lun = db('e_lun')->where('zt',1)->value('lun');
        if(!$num_lun){
            die('轮次错误，请联系技术查看');
        }
        $lists=db('e_list')->where('lun',$num_lun)->order('time_zijin asc')->paginate(10);
        $this->assign('num_lun', $num_lun);
        $this->assign('lists', $lists);
        return view();
    }
    public function history(){    //已出局
        $lists=db('e_history')->where([])->order('id desc')->paginate(10);
        $this->assign('lists', $lists);
        return view();
    }
    public function truein(){    //参与列表
        $lists=db('e_true_in')->where([])->order('id desc')->paginate(10);
        $this->assign('lists', $lists);
        return view();
    }
    public function tilian_list(){   //提链列表
        $param = request()->param();
        $where = [];
        if(isset($param['status'])){
            if($param['status']<>'all'){
                $where['status']=$param['status'];
            }
        }else{
            $where['status']=0;
        }

        $lists = db('e_true_out')->where($where)->order('id asc')->paginate(10);
        $sum['all'] = db('e_true_out')->where([])->sum('money');
        $sum['ok'] = db('e_true_out')->where('status',1)->sum('money');
        $sum['ing'] = db('e_true_out')->where('status',3)->sum('money');
        $max_nonce = $this->setting['e_nonce'];
        $this->assign('sum', $sum);
        $this->assign('max_nonce', $max_nonce);
        $this->assign('lists', $lists);
        $this->assign('status', isset($param['status'])?$param['status']:'0');
        return view();
    }
    public function tilian_do(){   //提链执行
        $setting = $this->setting;
        $param = request()->param();
        $where = [];
        //合法性
        if(!isset($param['id'])){
            $this->error('非法请求！');
        }
        $item = db('e_true_out')->where('id',$param['id'])->find();
        if(!$item){
            $this->error('不存在！');
        }elseif(!in_array($item['status'],[0,2])){
            $this->error('请勿重复处理！'.$item['status']);
        }
        //接口执行转账
        $user_qb=db('adeth')->where('uname',$item['uname'])->find();
        $urlqb=config('coin_host2').'sendTransaction';
        $params['type']='gusd';
        $params['contract']=config('con_gusd');
        $params['from']=$setting['e_address'];
        $params['nonce']=$setting['e_nonce'];
        $params['key']=$setting['e_key'];
        $params['to']=$user_qb['address'];
        $params['value']=floatval($item['money']);  //去除小数点后多余0
        // $params['gas']=10;
        // die($urlqb.'?'.http_build_query($params));

        $retqb=http($urlqb,$params,'GET',30);
        if(!$retqb){
            $this->error('接口失败');
        }
        $retqb=json_decode($retqb,true);
        if($retqb && $retqb['status']==1 && $retqb['hash']){
            $ret1 = db('e_true_out')->where('id',$item['id'])->update([
                'status'=>3,
                'uptime'=>time(),
                'hash'=>$retqb['hash'],
                'nonce'=>$setting['e_nonce'],
            ]);
            $ret2 = db('setting')->where('key','e_nonce')->setInc('val');
            if($ret1 && $ret2){
                $this->success('执行成功');
            }else{
                $this->error('提链成功，但写入失败!!');
            }
        }else{
            db('e_true_out')->where('id',$item['id'])->update([
                'status'=>2,
                'uptime'=>time(),
            ]);
            $this->error('提链失败');
        }
    }
    public function tilian_status(){    //提链结果手动查询
        $param = request()->param();
        $where = [];
        //合法性
        if(!isset($param['id'])){
            $this->error('非法请求！');
        }
        $item = db('e_true_out')->where('id',$param['id'])->find();
        if(!$item){
            $this->error('不存在！');
        }elseif($item['status']<>3){
            $this->error('请勿重复查询！');
        }

        $urlqb=config('coin_host2').'getTransactionHash';
        $params['hash']=$item['hash'];
        $ret_qb=http($urlqb,$params,'GET');
        $ret_qb=json_decode($ret_qb,true);
        // dump($ret_qb);
        // dump($ret_qb['hash']['status']);
        // dump($ret_qb['hash']['gasUsed']);
        // dump($ret_qb['hash']['logs'][0]['blockNumber']);
        // die();
        if($ret_qb && isset($ret_qb['hash']['status']) && $ret_qb['hash']['status']){
            db('e_true_out')->where('id',$item['id'])->update([
                'status'=>1,
                'blocknumber'=>$ret_qb['hash']['logs'][0]['blockNumber'],
                'gasused'=>$ret_qb['hash']['gasUsed']
            ]);
            $this->success('已到账');
        }else{
            $this->success('还未到账');
        }
    }

    public function tilian_nonce(){ //修正nonce
        $param = request()->param();
        if (!isset($param['nonce'])) {
            $this->error('请输入修正内容');
        }
        $param['nonce'] = intval($param['nonce']);
        if($param['nonce']<=0){
            $this->error('请输入正数');
        }
        $ret = db('setting')->where('key','e_nonce')->update(['val'=>$param['nonce']]);
        if($ret){
            $this->success('修改成功，请调试提链');
        }else{
            $this->error('修改失败');
        }
    }
    public function dong(){    //动态记录
        $lists=db('e_log_dong')->where([])->order('id desc')->paginate(10);
        $this->assign('lists', $lists);
        return view();
    }

    public function jinzijin(){    //进入资金池
        // $this->error('稍后再试');

        $setting = $this->setting;
        $param = request()->param();
        if(!isset($param['id'])){
            $this->error('参数不正确');
        }
        $list = db('e_list')->where('id',$param['id'])->find();
        if(!$list){
            $this->error('找不到该笔订单');
        }
        $num_lun = db('e_lun')->where('zt',1)->value('lun');
        if(!$num_lun){
            $this->error('轮次错误，请联系技术查看');
        }elseif($list['zt']==3){
            $this->error('该单已经撤回');
        }
        $userinfo = userinfobyid($list['uid']);
        
        Db::startTrans();   // 启动事务-------------
        //进入资金池
        $ret_zijin = db('e_list')->where('id',$param['id'])->update([
            'time_zijin'=>time(),
            'lun'=>$num_lun,
        ]);
        //E用户信息改变
        $ret_user = db('e_user')->where('uid',$list['uid'])->inc('sumdan')->inc('sumtou',$list['money'])->update([
            'lastlun'=>$num_lun,
        ]);
        //轮次表记录
        $ret_lun = db('e_lun')->where('lun',$num_lun)->inc('sum_dan')->inc('sum_gusd',$list['money'])->update();
        //E奖金判断与发放
        //e_user表：上级$s_euser
        //e_list表:上级$s_elist 下级$x_elist
        $ret_jiangs = true;
        //判断上级
        $s_uname = $userinfo['tname'];
        $s_elist = db('e_list')->where('uname',$s_uname)->where('lun',$num_lun)->order('money desc')->find();   //选最大额度一单
        $s_euser = db('e_user')->where('uname',$s_uname)->find();
        if($s_elist && $s_euser){
            $x_elist = $list;
            $shaoshang = 0;
            $jiang = round($x_elist['money']*$setting['e_dong']/100,2);
            $note = '';
            if($x_elist['money']>$s_elist['money']){
                $shaoshang = round($jiang - $jiang*($s_elist['money']/$x_elist['money']),2);
                $jiang = round($jiang*($s_elist['money']/$x_elist['money']),2);
                $note = '(烧伤)';
            }
            $ret_jiang_dong = db('e_log_dong')->insert([
                'uid'=>$s_euser['uid'],
                'uname'=>$s_euser['uname'],
                'mqian'=>$s_euser['gusd'],
                'money'=>$jiang,
                'mhou'=>$s_euser['gusd']+$jiang,
                'note'=>'E奖金'.$note,
                'time'=>time(),
                'oid'=>$x_elist['trueid'],  //因转入历史后elist的id就没了，所以标记这个id
                'oname'=>$x_elist['uname'],
                'lun'=>$num_lun,
                'zjtz'=>$s_elist['money'],
                'xjtz'=>$x_elist['money'],
            ]);
            $ret_jiang_user = db('e_user')->where('uname',$s_euser['uname'])->setInc('gusd',$jiang);
            if($shaoshang == 0){
                $ret_jiang_lun = db('e_lun')->where('lun',$num_lun)->inc('sum_dong',$jiang)->update();
            }else{
                $ret_jiang_lun = db('e_lun')->where('lun',$num_lun)->inc('sum_dong',$jiang)->inc('sum_shao',$shaoshang)->update();
            }
            if(!$ret_jiang_dong || !$ret_jiang_user || !$ret_jiang_lun){
                $ret_jiangs = false;
            }
        }

        //判断下级（直推） 拿下级的奖金
        //如果是第一次进该轮，判断直推们，因为上级第二次进不会再次拿下级奖金
        $sum_list = db('e_list')->where('uname',$list['uname'])->where('lun',$num_lun)->count();
        if ($sum_list==1) {
            $zt_unames=db('user')->where('tid',$userinfo['id'])->column('uname');
            foreach ($zt_unames as $zt_uname) {
                $x_elist = db('e_list')->where('uname',$zt_uname)->where('lun',$num_lun)->find();   //下级投了多单还没判断
                if($x_elist){
                    $s_elist = $list;
                    $s_euser = db('e_user')->where('uname',$list['uname'])->find();
                    $shaoshang = 0;
                    $jiang = round($x_elist['money']*$setting['e_dong']/100,2);
                    $note = '';
                    if($x_elist['money']>$s_elist['money']){
                        $shaoshang = round($jiang - $jiang*($s_elist['money']/$x_elist['money']),2);
                        $jiang = round($jiang*($s_elist['money']/$x_elist['money']),2);
                        $note = '(烧伤)';
                    }
                    $ret_jiang_dong = db('e_log_dong')->insert([
                        'uid'=>$s_euser['uid'],
                        'uname'=>$s_euser['uname'],
                        'mqian'=>$s_euser['gusd'],
                        'money'=>$jiang,
                        'mhou'=>$s_euser['gusd']+$jiang,
                        'note'=>'E奖金'.$note,
                        'time'=>time(),
                        'oid'=>$x_elist['trueid'],  //因转入历史后elist的id就没了，所以标记这个id
                        'oname'=>$x_elist['uname'],
                        'lun'=>$num_lun,
                        'zjtz'=>$s_elist['money'],
                        'xjtz'=>$x_elist['money'],
                    ]);
                    $ret_jiang_user = db('e_user')->where('uname',$s_euser['uname'])->setInc('gusd',$jiang);
                    if($shaoshang == 0){
                        $ret_jiang_lun = db('e_lun')->where('lun',$num_lun)->inc('sum_dong',$jiang)->update();
                    }else{
                        $ret_jiang_lun = db('e_lun')->where('lun',$num_lun)->inc('sum_dong',$jiang)->inc('sum_shao',$shaoshang)->update();
                    }
                    if(!$ret_jiang_dong || !$ret_jiang_user || !$ret_jiang_lun){
                        $ret_jiangs = false;
                    }
                }
            }
        }
            

        if($ret_zijin && $ret_user && $ret_lun && $ret_jiangs){
            Db::commit();       // 提交事务-------------
            $this->success('进入成功');
        }else{
            Db::rollback();     // 回滚事务-------------
            $this->error('进入失败'.$ret_zijin.$ret_user.$ret_lun.$ret_jiangs);
        }
    }

    public function chuju(){    //快速正常出局
        $setting = $this->setting;
        $param = request()->param();
        if(!isset($param['id'])){
            $this->error('参数不正确');
        }
        $list = db('e_list')->where('id',$param['id'])->find();
        if(!$list){
            $this->error('找不到该笔订单');
        }
        $num_lun = db('e_lun')->where('zt',1)->value('lun');
        if(!$num_lun || $list['lun']<>$num_lun){
            $this->error('轮次错误，请联系技术查看'.$list['lun']);
        }elseif($list['zt']<>0){
            $this->error('状态错误，请联系技术查看'.$list['zt']);
        }
        $time_chuju = $list['time_zijin'] + $setting['e_t']*86400;
        if($time_chuju>=time()){
            $this->error('出局时间还未到'.date('Y-m-d H:i:s',$time_chuju));
        }
        $userinfo = userinfobyid($list['uid']);
        $einfo = db('e_user')->where('uid',$list['uid'])->find();
        if(!$userinfo || !$einfo){
            $this->error('用户信息错误');
        }
        Db::startTrans();   // 启动事务-------------
        //修改状态
        $money_end = $list['money']+$list['money']*($setting['e_li']/100);
        $ret_list = db('e_list')->where('id',$list['id'])->update([
            'zt'=>'1',
            'time_end'=>$time_chuju,
            'money_end'=>$money_end,
            'mqian'=>$einfo['gusd'],
            'mhou'=>$einfo['gusd']+$money_end,
        ]);
        //增加余额
        $ret_user = db('e_user')->where('uid',$list['uid'])->setInc('gusd',$money_end);
        //轮次信息
        $jijin = $list['money']*($setting['e_li']/100)*($setting['e_jijin']/100);
        $ret_lun = db('e_lun')->where('lun',$num_lun)
            ->inc('sum_chuju_dan',1)
            ->inc('sum_chuju_gusd',$money_end)
            ->inc('sum_jijin',$jijin)
            ->update();
        if($ret_list && $ret_user && $ret_lun){
            Db::commit();       // 提交事务-------------
            $this->success('出局成功');
        }else{
            Db::rollback();     // 回滚事务-------------
            $this->error('出局失败'.$ret_list.$ret_user.$ret_lun);
        }
    }

}
